#include "./header/pulldata.h"
#include "ui_pulldata.h"
#include <QFile>
#include <QtCore>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptValueIterator>

PullData::PullData(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::PullData)
{
    ui->setupUi(this);
    nam = new QNetworkAccessManager(this);
    connect(nam,SIGNAL(finished(QNetworkReply*)),this,SLOT(finished(QNetworkReply*)));
}

PullData::~PullData() {
    delete ui;
}

void PullData::getHttpGetData() {
    QString baseString = "http://query.yahooapis.com/v1/public/yql?q=select symbol, Ask from yahoo.finance.quotes where symbol in ('AAPL','GOOG','MSFT')&format=json&env=http://datatables.org//alltables.env";
    QString url = baseString;
    nam->get(QNetworkRequest(QUrl(url)));
}

void PullData::finished(QNetworkReply *reply) {
    if(reply->error() == QNetworkReply::NoError) {
        QByteArray result;
        result = reply->readAll();

        QScriptValue sc;
        QScriptEngine engine;

        sc = engine.evaluate("JSON.parse").call(QScriptValue(), QScriptValueList() << result.data());
        QScriptValue dataDownloaded = sc.property("query").toObject();
        QScriptValue results = dataDownloaded.property("results").toObject();
        QScriptValue quotes = results.property("quote").toObject();

        if (quotes.isArray()) {
            QScriptValueIterator it(quotes);
            while (it.hasNext()) {
                it.next();
                if (it.value().property("Ask").toString() != "" & it.value().property("symbol").toString() != "") {
                    QFile file;
                    QString data;
                    if (it.value().property("symbol").toString() == "GOOG") {
                        qDebug("GOOG %s",it.value().property("Ask").toString().toStdString().c_str());
                        data.append("GOOG");
                        data.append(",");
                        data.append(it.value().property("Ask").toString());
                        data.append(",");
                        QDateTime currentTime = QDateTime::currentDateTime();
                        data.append(currentTime.toString());
                        data.append("\n");
                        file.setFileName("/Users/pfn368/junk/mini-stock-exchange/google.dat");
                    }
                    else if (it.value().property("symbol").toString() == "AAPL") {
                        qDebug("AAPL %s",it.value().property("Ask").toString().toStdString().c_str());
                        file.setFileName("/Users/pfn368/junk/mini-stock-exchange/apple.dat");
                        data.append("AAPL");
                        data.append(",");
                        data.append(it.value().property("Ask").toString());
                        data.append(",");
                        QDateTime currentTime = QDateTime::currentDateTime();
                        data.append(currentTime.toString());
                        data.append("\n");
                    }
                    else if (it.value().property("symbol").toString() == "MSFT") {
                        qDebug("MSFT %s",it.value().property("Ask").toString().toStdString().c_str());
                        file.setFileName("/Users/pfn368/junk/mini-stock-exchange/microsoft.dat");
                        data.append("MSFT");
                        data.append(",");
                        data.append(it.value().property("Ask").toString());
                        data.append(",");
                        QDateTime currentTime = QDateTime::currentDateTime();
                        data.append(currentTime.toString());
                        data.append("\n");
                    }
                    else {
                        qDebug() << "THIS SHOULD NEVER HAPPEN";
                    }
                    if (!file.open(QIODevice::Append)) {
                        qDebug() << "File cannot be opened in Append mode, generateRandom function!" << endl;
                    }
                    //QTextStream out(&file);out << data;
                    ui->responseText->setText(ui->responseText->toPlainText() + data);
                    file.flush();
                    file.close();
                }
            }
        }
    }
    else {
        ui->responseText->setText(reply->errorString());
    }
}
